package com.hy.mechanicalarm.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hy.mechanicalarm.R;
import com.hy.mechanicalarm.baseapp.BaseFragment;
import com.hy.mechanicalarm.constant.Constants;
import com.hy.mechanicalarm.ui.activity.SettingActivity;
import com.hy.mechanicalarm.ui.bean.AngleCalResult;
import com.hy.mechanicalarm.ui.service.SocketService;
import com.hy.mechanicalarm.ui.view.MenuViewItem;
import com.hy.mechanicalarm.ui.view.VerticalSeekBar;
import com.hy.mechanicalarm.utils.AngleCalUtil;
import com.hy.mechanicalarm.utils.CommonUtil;
import com.hy.mechanicalarm.utils.SPUtil;

import butterknife.BindView;

/**
 *  2018/8/7 15:20
 *  hanyin
 *  hanyinit@163.com
 */
public class JWSettingFragment extends BaseFragment implements View.OnClickListener,VerticalSeekBar.OnSeekBarChangeListener,RadioGroup.OnCheckedChangeListener{

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
   @BindView(R.id.menu_1)
   MenuViewItem menuItem1;
   @BindView(R.id.menu_2)
   MenuViewItem menuItem2;
   @BindView(R.id.menu_3)
   MenuViewItem menuItem3;
   @BindView(R.id.layoutSeekbar)
   LinearLayout layoutSeekbar;
   @BindView(R.id.rb_clw)
   RadioButton rb_clw;
   @BindView(R.id.rb_tjw)
   RadioButton rb_tjw;
   @BindView(R.id.verticalSeekBar)
   VerticalSeekBar verticalSeekBar;
   @BindView(R.id.tvSeekbar)
   TextView tvSeekbar;
   @BindView(R.id.imageJia)
   ImageView imageJia;
   @BindView(R.id.imageJian)
   ImageView imageJian;
   int max = 100;
   @BindView(R.id.tvMax)
   TextView tvMax;
   boolean menu_1 = false;
   boolean menu_2 = false;
   boolean menu_3 = false;
   @BindView(R.id.radioGroup)
   RadioGroup radioGroup;
//   private String  setMeasureOrder= "AA55001201xyz000eCC33";
   private String  setMeasureOrder= "001201xyz";
//   private String  setstopOrder   = "AA55001202xyz000eCC33";
   private String  setstopOrder   = "001202xyz";
    public JWSettingFragment() {
    }

    private LocalBroadcastManager mLocalBroadcastManager;
    private MessageBackReciver mReciver;
    private IntentFilter mIntentFilter;
    SPUtil spUtil ;




    class MessageBackReciver extends BroadcastReceiver {

        public MessageBackReciver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SocketService.HEART_BEAT_ACTION)) {
            } else {
                String message = intent.getStringExtra("message");
                if("01".equals(message.substring(8,10))){
                    //设置测量位
                    String data = message.substring(14,18);
                    if("0000".equals(data)){
                        CommonUtil.showToast("设置测量位");
                    }
                }else if("02".equals(message.substring(8,10))){
                    //设置停机位
                    String data = message.substring(14,18);
                    if("0000".equals(data)){
                        CommonUtil.showToast("设置停机位");
                    }
                }
            }
        }
    }
    public static JWSettingFragment newInstance(String param1, String param2) {
        JWSettingFragment fragment = new JWSettingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        layoutSeekbar.setVisibility(View.GONE);
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        mReciver = new MessageBackReciver();
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(SocketService.HEART_BEAT_ACTION);
        mIntentFilter.addAction(SocketService.MESSAGE_ACTION);
        mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);

    }

    @Override
    public void initData() {
        super.initData();
        spUtil = new SPUtil(getActivity());
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
   public void initListener() {
       super.initListener();
       menuItem1.setOnClickListener(this);
       menuItem2.setOnClickListener(this);
       menuItem3.setOnClickListener(this);
       verticalSeekBar.setOnSeekBarChangeListener(this);
       imageJia.setOnClickListener(this);
       imageJian.setOnClickListener(this);
       radioGroup.setOnCheckedChangeListener(this);
   }



    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_jwsetting;
    }

    @Override
    protected void loadData() {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.menu_1:
                if(rb_clw.isChecked()||rb_tjw.isChecked()){
                    menuItem1.setBackground(getResources().getDrawable(R.drawable.jw_5));
                    menuItem3.setBackground(getResources().getDrawable(R.drawable.jw_6));
                    menuItem2.setBackground(getResources().getDrawable(R.drawable.jw_3));

                    layoutSeekbar.setVisibility(View.VISIBLE);
                    verticalSeekBar.setMax(360);
                    tvMax.setText(360+"");
                    if(rb_clw.isChecked()){
                        String MEASURE_X = spUtil.getString(Constants.MEASURE_X,"0");
                        verticalSeekBar.setProgress(Integer.valueOf(MEASURE_X));
                        verticalSeekBar.refreshView(Integer.valueOf(MEASURE_X));
                        tvSeekbar.setText(MEASURE_X);
                    }
                    if(rb_tjw.isChecked()){
                        String GATE_POSITION_X = spUtil.getString(Constants.GATE_POSITION_X,"0");
                        verticalSeekBar.setProgress(Integer.valueOf(GATE_POSITION_X));
                        verticalSeekBar.refreshView(Integer.valueOf(GATE_POSITION_X));
                        tvSeekbar.setText(GATE_POSITION_X);
                    }
                    menu_1 = true;
                    menu_2 = false;
                    menu_3 = false;
                }
                break;
            case R.id.menu_2:
                if(rb_clw.isChecked()||rb_tjw.isChecked()){
                    menuItem1.setBackground(getResources().getDrawable(R.drawable.jw_7));
                    menuItem2.setBackground(getResources().getDrawable(R.drawable.jw_4));
                    menuItem3.setBackground(getResources().getDrawable(R.drawable.jw_3));
                    layoutSeekbar.setVisibility(View.VISIBLE);
                    verticalSeekBar.setMax(80);
                    tvMax.setText(80+"");
                    if(rb_clw.isChecked()){
                        String MEASURE_Y = spUtil.getString(Constants.MEASURE_Y,"0");
                        verticalSeekBar.setProgress(Integer.valueOf(MEASURE_Y));
                        verticalSeekBar.refreshView(Integer.valueOf(MEASURE_Y));
                        tvSeekbar.setText(MEASURE_Y);
                    }
                    if(rb_tjw.isChecked()){
                        String GATE_POSITION_Y = spUtil.getString(Constants.GATE_POSITION_Y,"0");
                        verticalSeekBar.setProgress(Integer.valueOf(GATE_POSITION_Y));
                        verticalSeekBar.refreshView(Integer.valueOf(GATE_POSITION_Y));
                        tvSeekbar.setText(GATE_POSITION_Y);
                    }
                    menu_1 = false;
                    menu_2 = true;
                    menu_3 = false;
                }
                break;
            case R.id.menu_3:
                if(rb_clw.isChecked()||rb_tjw.isChecked()){
                    menuItem1.setBackground(getResources().getDrawable(R.drawable.jw_7));
                    menuItem2.setBackground(getResources().getDrawable(R.drawable.jw_5));
                    menuItem3.setBackground(getResources().getDrawable(R.drawable.jw_2));
                    layoutSeekbar.setVisibility(View.VISIBLE);
                    verticalSeekBar.setMax(80);
                    tvMax.setText(80+"");
                    if(rb_clw.isChecked()){
                        String MEASURE_Z = spUtil.getString(Constants.MEASURE_Z,"0");
                        verticalSeekBar.setProgress(Integer.valueOf(MEASURE_Z));
                        verticalSeekBar.refreshView(Integer.valueOf(MEASURE_Z));
                        tvSeekbar.setText(MEASURE_Z);
                    }
                    if(rb_tjw.isChecked()){
                        String GATE_POSITION_Z = spUtil.getString(Constants.GATE_POSITION_Z,"0");
                        verticalSeekBar.setProgress(Integer.valueOf(GATE_POSITION_Z));
                        verticalSeekBar.refreshView(Integer.valueOf(GATE_POSITION_Z));
                        tvSeekbar.setText(GATE_POSITION_Z);
                    }
                    menu_1 = false;
                    menu_2 = false;
                    menu_3 = true;
                }
                break;
            case R.id.imageJia:
                int progressJia = 0;
                if(verticalSeekBar.getProgress()==max){
                   CommonUtil.showToast("已经是最大值");
                }else{
                    progressJia = verticalSeekBar.getProgress()+1;
                    tvSeekbar.setText(progressJia+"");
                    verticalSeekBar.refreshView(progressJia);
                    sendOrder(progressJia);

                }
                break;
            case R.id.imageJian:
                int progressJian = 0;
                if(verticalSeekBar.getProgress()==0){
                    CommonUtil.showToast("已经是最小值");
                }else{
                    progressJian = verticalSeekBar.getProgress()-1;
                    tvSeekbar.setText(progressJian+"");
                    verticalSeekBar.refreshView(progressJian);
                    sendOrder(progressJian);
                }
                break;
        }
    }

    /**
     * 补齐参数
     * @param parame
     * @return
     */
    public String  polishingParame(String parame){
        StringBuffer sb = new StringBuffer();

        if(parame.length()==1){
            sb.append("0000");
        }else if(parame.length()==2){
            sb.append("00");
        }
        for (int i = 0; i <parame.length(); i++) {
            sb.append("0"+parame.charAt(i));
        }
        return sb.toString();
    }

    public String makeChecksum(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
//            System.out.println(s);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
         * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len == 2) {
            hex = "00" + hex;
        }else if (len == 1) {
            hex = "000" + hex;
        }else if (len == 3) {
            hex = "0" + hex;
        }
        return hex;
    }
    private void sendOrder(int parame) {
        String MEASURE_X = spUtil.getString(Constants.MEASURE_X,"0");
        String MEASURE_Y = spUtil.getString(Constants.MEASURE_Y,"0");
        String MEASURE_Z = spUtil.getString(Constants.MEASURE_Z,"0");
        String GATE_POSITION_X = spUtil.getString(Constants.GATE_POSITION_X,"0");
        String GATE_POSITION_Y = spUtil.getString(Constants.GATE_POSITION_Y,"0");
        String GATE_POSITION_Z = spUtil.getString(Constants.GATE_POSITION_Z,"0");
        boolean isDetermineScope = true;
        if(rb_clw.isChecked()){
            if(menu_1){
                MEASURE_X = parame+"";
                spUtil.putString(Constants.MEASURE_X,MEASURE_X);
            }else if(menu_2){
                MEASURE_Y = parame+"";
                spUtil.putString(Constants.MEASURE_Y,MEASURE_Y);
                isDetermineScope =  determineScope(Integer.valueOf(MEASURE_Y),Integer.valueOf(MEASURE_Z));
            }else if(menu_3){
                MEASURE_Z = parame+"";
                spUtil.putString(Constants.MEASURE_Z,MEASURE_Z);
                isDetermineScope = determineScope(Integer.valueOf(MEASURE_Y),Integer.valueOf(MEASURE_Z));
            }

            String x =  setMeasureOrder.replace("x",polishingParame(MEASURE_X));
            String y =  x.replace("y",polishingParame(MEASURE_Y));
            String z =  y.replace("z",polishingParame(MEASURE_Z));

            z += makeChecksum(z);
            if (isDetermineScope) {
                ((SettingActivity) getActivity()).socketService.sendMsg("AA55" + z + "CC33");
            }
        }else if(rb_tjw.isChecked()){
            if(menu_1){
                GATE_POSITION_X = parame+"";
                spUtil.putString(Constants.GATE_POSITION_X,GATE_POSITION_X);
            }else if(menu_2){
                GATE_POSITION_Y = parame+"";
                spUtil.putString(Constants.GATE_POSITION_Y,GATE_POSITION_Y);
                isDetermineScope = determineScope(Integer.valueOf(GATE_POSITION_Y),Integer.valueOf(GATE_POSITION_Z));
            }else if(menu_3){
                GATE_POSITION_Z = parame+"";
                spUtil.putString(Constants.GATE_POSITION_Z,GATE_POSITION_Z);
                isDetermineScope = determineScope(Integer.valueOf(GATE_POSITION_Y),Integer.valueOf(GATE_POSITION_Z));
            }
            String x =  setstopOrder.replace("x",polishingParame(GATE_POSITION_X));
            String y =  x.replace("y",polishingParame(GATE_POSITION_Y));
            String z =  y.replace("z",polishingParame(GATE_POSITION_Z));

            z += makeChecksum(z);
            if (isDetermineScope){
                ((SettingActivity)getActivity()).socketService.sendMsg("AA55"+z+"CC33");
            }
        }
    }

    private boolean determineScope(int y, int z) {
        AngleCalResult angleCalResult =  AngleCalUtil.angleCal(Integer.valueOf(y),Integer.valueOf(z));
        if(angleCalResult.getCode()==AngleCalResult.CODE_SUCCESS){
                return true;
        }else if(angleCalResult.getCode()==AngleCalResult.CODE_FAIL){
            CommonUtil.showToast("请将上臂移到 "+angleCalResult.getRangeMin()+" 到 "+angleCalResult.getRangeMax()+" 的范围");
            return false;
        }
        return false;
    }

    @Override
    public void onStop() {
        super.onStop();
        mLocalBroadcastManager.unregisterReceiver(mReciver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        tvSeekbar.setText(progress+"");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        sendOrder(verticalSeekBar.getProgress());
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.rb_clw:
                if(menu_1){
                    String MEASURE_X = spUtil.getString(Constants.MEASURE_X,"0");
                    verticalSeekBar.setProgress(Integer.valueOf(MEASURE_X));
                    verticalSeekBar.refreshView(Integer.valueOf(MEASURE_X));
                    tvSeekbar.setText(MEASURE_X);
                }else if(menu_2){
                    String MEASURE_Y = spUtil.getString(Constants.MEASURE_Y,"0");
                    verticalSeekBar.setProgress(Integer.valueOf(MEASURE_Y));
                    verticalSeekBar.refreshView(Integer.valueOf(MEASURE_Y));
                    tvSeekbar.setText(MEASURE_Y);
                }else if(menu_3){
                    String MEASURE_Z = spUtil.getString(Constants.MEASURE_Z,"0");
                    verticalSeekBar.setProgress(Integer.valueOf(MEASURE_Z));
                    verticalSeekBar.refreshView(Integer.valueOf(MEASURE_Z));
                    tvSeekbar.setText(MEASURE_Z);
                }
                break;
            case R.id.rb_tjw:
                if(menu_1){
                    String GATE_POSITION_X = spUtil.getString(Constants.GATE_POSITION_X,"0");
                    verticalSeekBar.setProgress(Integer.valueOf(GATE_POSITION_X));
                    verticalSeekBar.refreshView(Integer.valueOf(GATE_POSITION_X));
                    tvSeekbar.setText(GATE_POSITION_X);
                }else if(menu_2){
                    String GATE_POSITION_Y = spUtil.getString(Constants.GATE_POSITION_Y,"0");
                    verticalSeekBar.setProgress(Integer.valueOf(GATE_POSITION_Y));
                    verticalSeekBar.refreshView(Integer.valueOf(GATE_POSITION_Y));
                    tvSeekbar.setText(GATE_POSITION_Y);
                }else if(menu_3){
                    String GATE_POSITION_Z = spUtil.getString(Constants.GATE_POSITION_Z,"0");
                    verticalSeekBar.setProgress(Integer.valueOf(GATE_POSITION_Z));
                    verticalSeekBar.refreshView(Integer.valueOf(GATE_POSITION_Z));
                    tvSeekbar.setText(GATE_POSITION_Z);
                }
                break;
        }

    }
}
